<?php

function asocam_preprocess_simplenews_newsletter_body(&$variables) {
	require_once(libraries_get_path('emogrifier') . '/emogrifier.php');
  $variables['title'] = check_plain($variables['node']->title);
  // using emogrify, loading css from file
  $css = file_get_contents(drupal_get_path('theme', 'asocam') . '/css/mail.css');
  $emo = new Emogrifier();
  $emo->setCSS($css);
  $emo->setHTML(asocam_body_simplenews($variables));
  $variables['body'] = $emo->emogrify();
}




function asocam_preprocess_node(&$vars, $hook) {
  $function = __FUNCTION__ . '_' . $vars['node']->type;
  if (function_exists($function)) {
    $function($vars, $hook);
  }
}

function asocam_preprocess_node_simplenews(&$vars, $hook) {
  $vars['content'] = asocam_body_simplenews($vars);
}

function asocam_body_simplenews($vars) {
  $node = $vars['node'];
  $args_noticias = asocam_array2args($node->field_noticias);
  $args_eventos = asocam_array2args($node->field_eventos);
  $args_publicaciones = asocam_array2args($node->field_publicacion);    
	$output  = "<div class=\"full-body\">";
  $output .= theme('imagecache', '600x250', $node->field_imagen[0]['filepath']);
	$output .= "<div class=\"simplenews-body\">" . $vars['node']->content['body']['#value'] . "</div>";
  // check if you have items for each section
	if (!is_null($node->field_publicacion[0]['nid'])) {
    $output .= "<h3>" . 'Publicaciones' . '</h3>';
  	$output .= asocam_views_set_display('simplenews', 'block_1', 'publicacion', $args_publicaciones);
  }
  if (!is_null($node->field_noticias[0]['nid'])) {
  	$output .= "<h3>" . 'Noticias' . '</h3>';
  	$output .= asocam_views_set_display('simplenews', 'block_1', 'noticia', $args_noticias);
  }
  if (!is_null($node->field_eventos[0]['nid'])) {  
  	$output .= "<h3>" . 'Eventos' . '</h3>';	
  	$output .= asocam_views_set_display('simplenews', 'block_1', 'evento', $args_eventos);
	}
  $output .= theme('image', drupal_get_path('theme', 'asocam') . '/images/bulletin_footer.png');
	$output .= "</div>";
	return $output;
}

function asocam_array2args($items) {
  foreach ($items as $item) {
    $nids[] = $item['nid'];
  }
  return array(implode(',', $nids));
}

/*
 * try
 * $view = views_get_view('foobar'); 
 * $view->set_display('display_id');
 * $view->filter['filter_id']->value = 'newvalue';
 * 
 *   $view=views_get_view('myview');
 *   $view->add_display('block',$alias,$new_display);
 *       $view->display[$new_display]->display_title = $alias;
 *   $view->display[$new_display]->position = $number+1;
 *   $view->display[$new_display]->vid = $view->display['default']->vid;
 * $view->save();
 */
function asocam_views_set_display($viewname, $display_id, $content_type, $args){
	$view = views_get_view($viewname);
  $view->set_display($display_id);
  $view->set_arguments($args);  
  //$view->display[$display_id]->handler->options['title'] = $content_type;
  //$view->display[$display_id]->handler->override_option('title', 'holaa');
  // remember this structure function add_item($display_id, $type, $table, $field, $options = array(), $id = NULL)
  $id = $view->add_item($display_id, 'filter', 'node', 'type');
  $item = $view->get_item($display_id, 'filter', $id);
  $item['value'] = array($content_type);
  $view->set_item($display_id, 'filter', $id, $item);
  $view->is_cacheable = FALSE;
  // set title
  $output = $view->execute_display($display_id);
  return $output['content'];  
}

function asocam_preprocess_search_theme_form(&$vars, $hook) {
  // Remove the "Search this site" label from the form.
  $vars['form']['search_theme_form']['#title'] = t('');
  
  // Set a default value for text inside the search box field.
  $vars['form']['search_theme_form']['#value'] = t('Search this Site');
  
  // Add a custom class and placeholder text to the search box.
  $vars['form']['search_theme_form']['#attributes'] = array('class' => 'NormalTextBox txtSearch', 
                                                              'onfocus' => "if (this.value == 'Search this Site') {this.value = '';}",
                                                              'onblur' => "if (this.value == '') {this.value = 'Search this Site';}");
  
  // Change the text on the submit button
  //$vars['form']['submit']['#value'] = t('Go');

  // Rebuild the rendered version (search form only, rest remains unchanged)
  unset($vars['form']['search_theme_form']['#printed']);
  $vars['search']['search_theme_form'] = drupal_render($vars['form']['search_theme_form']);

  #$vars['form']['submit']['#type'] = 'image_button';
  #$vars['form']['submit']['#src'] = path_to_theme() . '/images/search.jpg';
    
  // Rebuild the rendered version (submit button, rest remains unchanged)
  unset($vars['form']['submit']['#printed']);
  $vars['search']['submit'] = drupal_render($vars['form']['submit']);

  // Collect all form elements to make it easier to print the whole form.
  $vars['search_form'] = implode($vars['search']);
}

function asocam_preprocess_page(&$vars, $hook){
	if(arg(0) == 'videos' && is_numeric(arg(1))){
	  $vars['title'] = _myasocam_set_view_title(arg(1));
	}

	if(arg(0) == 'evento' && arg(1) == 'servicio' && is_numeric(arg(2))){
		$node_servicio = node_load(arg(2)); 
	  $vars['title'] = "Eventos sobre " . $node_servicio->title;
	}	

	if (module_exists('conditional_styles')) {
    $vars['styles'] = drupal_get_css($css);
    $vars['styles'] .= $vars['conditional_styles'];
  }
  $primary_links = $vars['primary_links'];
  $vars['primary_links'] =   $primary_links;
  $vars['main_menu_links'] = theme('links', $vars['primary_links'], array('class' => 'links main-menu'));
  
  //building of services menu
  $menu_services_links = menu_navigation_links('menu-services');
  
  $icons['Contactenos'] = theme('image', path_to_theme() . '/images/mail.png', $alt = '', $title = '', array('class' =>'icons'), $getsize = TRUE);
  $icons['Mapa de sitio'] = theme('image', path_to_theme() . '/images/sitemap.png', $alt = '', $title = '', array('class' =>'icons'), $getsize = TRUE);
  $icons['Buscar'] = theme('image', path_to_theme() . '/images/search.png', $alt = '', $title = '', array('class' =>'icons'), $getsize = TRUE);
   
  $icons['RSS'] = theme('image', path_to_theme() . '/images/rss.png', $alt = '', $title = '', array('class' =>'icons'), $getsize = TRUE);
  $icons['Facebook'] = theme('image', path_to_theme() . '/images/icon_facebook.png', $alt = '', $title = '', array('class' =>'icons'), $getsize = TRUE);
  $icons['Twitter'] = theme('image', path_to_theme() . '/images/icon_twitter.png', $alt = '', $title = '', array('class' =>'icons'), $getsize = TRUE);
  $icons['Youtube'] = theme('image', path_to_theme() . '/images/icon_youtube.png', $alt = '', $title = '', array('class' =>'icons'), $getsize = TRUE);
  $icons['Suscribase'] = theme('image', path_to_theme() . '/images/suscribase.png', $alt = '', $title = '', array('class' =>'icons'), $getsize = TRUE);  
  //dpm($menu_services_links);  
  foreach($menu_services_links as $k => $v){
    $menu_services_links[$k]['title'] = $icons[$menu_services_links[$k]['title']];
    $menu_services_links[$k]['html'] = TRUE;  
  }
  //dpm($menu_services_links);  
  $vars['services_menu_links'] = theme('links', $menu_services_links, array('class' => 'links services-menu-links'));
  $title = $vars['title'];
  if(arg(0) == 'servicio' && is_numeric(arg(2))) {
    $node = node_load(arg(2));
    $vars['title'] = $node->title;
    }
  if($vars['node']->type == 'service'){
    $vars['tabs'] =  $vars['tabs']  . asocam_display_tabs_services($vars['node']->nid);
    $vars['title'] = $vars['node']->title . ' >> ' . $vars['title'];
  }
  }
  
function asocam_preprocess_content_field(&$vars, $hook) {
  //add a template for image field
  $nodes = array('page', 'evento');
  
  if(in_array($vars['node']->type, $nodes)){
  array_unshift($vars['template_files'], 'content-field-field_imagen');
  }
  else{
  $templates = $vars['template_files'];
  foreach($templates as $template){
    if($template !== 'content-field-field_imagen'){
      $new_templates[] = $template; 
      }
    }
  $vars['template_files'] = $new_templates;
  }
  }

  
function asocam_menu_item($link, $has_children, $menu = '', $in_active_trail = FALSE, $extra_class = NULL) {
  $class = ($menu ? 'expanded' : ($has_children ? 'collapsed' : 'leaf'));
  if (!empty($extra_class)) {
    $class .= ' '. $extra_class;
  }
  if ($in_active_trail) {
    $class .= ' active-trail';
  }
  return '<li class="'. $class .'">'. $link . $menu ."</li>\n";
}  
  
  
/**
 * only works with two levels
 * return parent name of menu
 * menu link must be in only one menu, if you put a menu link in other menu you get error (0)
 */ 

function _asocam_get_name_parent_menu($nid) {
$sql = "SELECT plid, link_title FROM {menu_links} WHERE link_path LIKE '%%%d%%'";
$query = db_query($sql,$nid);
while($row = db_fetch_object($query)){
  $plid = $row->plid;
  $link_title = $row->link_title;
  }
if($plid == 0) {$output = $link_title;}
else {  
$sql2 = "SELECT link_title FROM {menu_links} WHERE mlid = $plid";
$menu_name = db_result(db_query($sql2));
$output = $menu_name;
}
return $output;
}

function _item_list($items, $id, $class){
  foreach($items as $item) {
    $output .= "<li>" . $item . "</li>\n";  
  }
  return "<div id=\"" . $id . "\"><ul class=\"" . $class . "\">" .  $output . "</ul></div>";
}

function _markup($element, $class) {
  return "<div class=\"" . $class . "\">" . $element ."</div>";
  }

function _month($month) {
  $months = array(
  '01' => 'Enero',
  '02' => 'Febrero',
  '03' => 'Marzo',
  '04' => 'Abril',
  '05' => 'Mayo',
  '06' => 'Junio',
  '07' => 'Julio',
  '08' => 'Agosto',
  '09' => 'Setiembre',
  '10' => 'Octubre',
  '11' => 'Noviembre',
  '12' => 'Diciembre',
  );
  return $months[$month];
  }


/**
 * this function modifies theme_item_list which is provided by default 
 * 
 */
  
function asocam_item_list($items = array(), $title = NULL, $type = 'ul', $attributes = NULL) {
  $output = '<div class="item-list">';
  //added by Adam to handle in images as links
  if (($attributes['rel'] == 'show-icons') && isset($attributes['rel'])) {
      $show_icons = TRUE;
      unset($attributes['rel']);
    }
    
  if (isset($title)) {
    $output .= '<h3>' . $title . '</h3>';
  }

  if (!empty($items)) {
    $output .= "<$type" . drupal_attributes($attributes) . '>';
    $num_items = count($items);
    foreach ($items as $i => $item) {
      $attributes = array();
      $children = array();
      if (is_array($item)) {
        foreach ($item as $key => $value) {
          if ($key == 'data') {
            $data = $value;
          }
          elseif ($key == 'children') {
            $children = $value;
          }
          else {
            $attributes[$key] = $value;
          }
        }
      }
      else {
        $data = $item;
      }
      if (count($children) > 0) {
        $data .= theme_item_list($children, NULL, $type, $attributes); // Render nested list
      }
      if ($i == 0) {
        $attributes['class'] = empty($attributes['class']) ? 'first' : ($attributes['class'] . ' first');
      }
      if ($i == $num_items - 1) {
        $attributes['class'] = empty($attributes['class']) ? 'last' : ($attributes['class'] . ' last');
      }
      //added by Adam to built empty links for social networks links
      if(isset($show_icons)) {
        $attributes['class'] = $attributes['class'] . ' ' . strip_tags($data);
        $link = replaceAnchorsWithText($data);
        $data = l(' ', $link);
      }
      $output .= '<li' . drupal_attributes($attributes) . '>' . $data . "</li>\n";
    }
    $output .= "</$type>";
  }
  $output .= '</div>';
  return $output;
}


function asocam_filefield_file($file) {
  // Views may call this function with a NULL value, return an empty string.
  if (empty($file['fid'])) {
    return '';
  }

  $path = $file['filepath'];
  $url = file_create_url($path);
  $icon = theme('filefield_icon', $file);

  // Set options as per anchor format described at
  // http://microformats.org/wiki/file-format-examples
  // TODO: Possibly move to until I move to the more complex format described 
  // at http://darrelopry.com/story/microformats-and-media-rfc-if-you-js-or-css
  $options = array(
    'attributes' => array(
      'type' => $file['filemime'] . '; length=' . $file['filesize'],
    ),
  );

  // Use the description as the link text if available.
  if (empty($file['data']['description'])) {
    $link_text = $file['filename'];
  }
  else {
    $link_text = $file['data']['description'];
    $options['attributes']['title'] = $file['filename'];
  }

  return '<div class="filefield-file">'. $icon . l('descargar documento', $url, $options) .'</div>';
}

function _asocam_get_list($items, $title){
	$color = '#23549B'; 
  $header = array();  // no se usa la cabecera porque produce un efecto jquery que no nos sirve
	$style_title = "font-size:25px; padding-left:10px; padding-top:6px; font-weight:bold; color: " . $color . "";
	$rows[] = array(array('data' => $title,'style' => $style_title, 'align' => 'left')); // funge de cabecera
	foreach($items as $item){
  $node = node_load($item['nid']);
  $rows[] = array(array('data' => _asocam_get_nodeview($node), 'style' => 'padding:10px')); 
  }
  $settings = 'border: solid 2px ' . $color . '; width:300px; margin:10px;';
  return theme('table', $header, $rows, array('style' => $settings));
}


function _asocam_get_nodeview($node){
  $titulo = $node->title;
  $content_types = array('noticia', 'evento');
  $teaser = in_array($node->type, $content_types) ? $node->body : $node->field_descripcion[0]['value'];
  $output  = theme('imagecache', '100x100', $node->field_imagen[0]['filepath'], $alt = '', $title = '', array('style' => 'float:left; margin-right:1em; margin-bottom: 1em;'));
  $output .= "<div style=\"width:150px; float:left\">" . l($titulo, 'node/' . $node->nid, array('attributes' => array('style' => 'text-decoration: none; color: #23549B; font-weight:bold; text-transform:uppercase; font-size:8pt')));
  $output .= "<p>" . node_teaser(strip_tags($teaser), 2, 100) . '...' . "</p>";
  $output .= l('Leer más', 'node/' . $node->nid, array('attributes' => array('style' => 'text-decoration:none; color:#23549B; font-size:8pt; font-weight:bold; float:right'))) . "</div>";
  return $output;
}

function asocam_breadcrumb($breadcrumb) {
  if (!empty($breadcrumb)) {
    return '<div class="breadcrumb">'. implode(' >> ', $breadcrumb) .'</div>';
  }
}

function asocam_taxonomy_term_view($terms, $vid, $title = ''){
	$items = array();
  foreach($terms as $term){
	  if($term->vid == $vid){
		  $items[] = l($term->name, 'taxonomy/term/' . $term->tid);
		}
	}
	$output = "<div class=\"field field-type-text field-field-". $title ."\">";
	$output .= "<div class=\"field-label\">". $title. ":&nbsp; </div>";
	$output .= "<div class=\"field-items\">" . implode(', ', $items) . "</div>";
	$output .= "</div>";
	return $output;
}




function asocam_display_tabs_services($nid){
	$node = node_load($nid);
	if($node->type == 'service'){
		$items['enfoque'] = l('Enfoque', 'node/' . $nid . '/enfoque');
		$items['servicios'] = l('Servicios', 'node/' . $nid . '/servicios');
		$items['cursos'] = l('Cursos y Eventos', 'node/' . $nid . '/cursos');
		$items['publicaciones'] = l('Publicaciones', 'node/' . $nid . '/publicaciones');
		$items['especialistas'] = l('Especialistas', 'node/' . $nid . '/especialistas');
		$tabs = theme('item_list', $items, '', $type = 'ul', array('class' => 'tabs secondary', 'id' => 'tabs_servicios'));
	}
	else {
	  $tabs = '';	
	}
	return $tabs;
}

function banner() {
  $options = array('params' => array('height' => 190, 'width' => 960));
  // return swf('http://www.asocam.net' . base_path() . path_to_theme() . '/header_asocam.swf', $options) ;
  return swf('http://' . $_SERVER['SERVER_NAME'] . base_path() . path_to_theme() . '/header_asocam.swf', $options) ;
  }
